﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Configuration;
using CompanyBussiness;


namespace Website.admin
{
    public partial class cCategoryCreate : System.Web.UI.UserControl
    {
        NewsManagement newsMana = new NewsManagement();
        LanguagesManagement languageMana = new LanguagesManagement();
        CompanyBussiness.Category category;
        CompanyBussiness.Language language;
        CheckValid cv = new CheckValid();
        string strFileName = "";
        bool AddOrUp = false;
        int STRcategoryID;
        string error = "";
        string modulCode;
        bool ImgStatus = true;

        protected void Page_Load(object sender, EventArgs e)
        {
            modulCode = Request.QueryString["Mod"];
            loadModul();
            if (Request.Cookies[CONST.COOKIES_LANGUAGE] == null)
            {
                Session[CONST.SESSION_LANGUAGE] = "";
                language = languageMana.GetLanguageByCode("vi-VN");
            }
            else
            {
                Session[CONST.SESSION_LANGUAGE] = Request.Cookies[CONST.COOKIES_LANGUAGE][CONST.COOKIES_LANGUAGE_ID];
                language = languageMana.GetLanguageByID(int.Parse(Session[CONST.COOKIES_LANGUAGE].ToString()));
            }

            
            this.LoadDropLanguage();
            this.LoadDropParentCategory();

            if (Request[CONST.QUERYSTRING_CATEGORY] == null || Request.Cookies[CONST.ACTION][CONST.COOKIES_ACTION_TYPE] == "AddCategory")
            {
                AddOrUp = false;
                //btnDelete.Visible = false;
                //linkBack.Visible = false;
                lbTypeAction.Text = "Tạo mới danh mục ";
            }
            else
            {
                AddOrUp = true;
                STRcategoryID = int.Parse(Request[CONST.QUERYSTRING_CATEGORY]);
                this.LoadForm();
                dropLanguage.Enabled = true;
                imgCategory.Visible = true;
                lbTypeAction.Text = "Cập nhật danh mục ";
            }
            
            fail.Visible = false;
            success.Visible = false;
        }

        protected void loadModul()
        {
            switch (modulCode)
            {
                case "MNEWS":
                    {
                        trPic.Style.Add("display","none");
                        trPicStatus.Style.Add("display", "none");
                        trDes.Style.Add("display", "none");
                        trDes2.Style.Add("display", "none");
                    }
                    break;
                case "MSHAREHOLDERS":
                    {
                        trPic.Style.Add("display", "none");
                        trPicStatus.Style.Add("display", "none");
                        trDes.Style.Add("display", "none");
                        trDes2.Style.Add("display", "none");
                    }
                    break;
                case "MJOB":
                    {
                        trPic.Style.Add("display", "none");
                        trPicStatus.Style.Add("display", "none");
                        trDes.Style.Add("display", "none");
                        trDes2.Style.Add("display", "none");
                    }
                    break;
                case "MHELP":
                    {
                        trPic.Style.Add("display", "none");
                        trPicStatus.Style.Add("display", "none");
                        trDes.Style.Add("display", "none");
                        trDes2.Style.Add("display", "none");
                    }
                    break;
                case "MCONTACT":
                    {

                    }
                    break;
                case "MINTRO":
                    {

                    }
                    break;
            }


        }

        protected void FormatForm()
        {
            try
            {
                if (AddOrUp == false)
                {
                    txtCategoryName.Text = "";
                    txtCategoryIntro.Text = "";
                    imgCategory.ImageUrl = ConfigurationManager.AppSettings["NoImages"];
                    txtCategoryDes.Value = "";
                    Session[CONST.SESSION_IMG] = null;
                    Session[CONST.SESSION_IMG_THUMBNAIL] = null;
                }
                else
                {
                    this.LoadForm();
                    Session[CONST.SESSION_IMG] = null;
                    Session[CONST.SESSION_IMG_THUMBNAIL] = null;
                }
            }
            catch (Exception)
            { }        
        }

        protected void LoadDropLanguage()
        {
            try
            {
                dropLanguage.Items.Clear();

                dropLanguage.DataSource = languageMana.GetLanguageList(true);
                dropLanguage.DataBind();

                if (Request.Cookies[CONST.COOKIES_LANGUAGE] != null)
                {
                    dropLanguage.SelectedValue = Request.Cookies[CONST.COOKIES_LANGUAGE][CONST.COOKIES_LANGUAGE_ID];
                }
            }
            catch (Exception)
            {
                fail.Visible = true;
                if (error != string.Empty)
                {
                    error = "Có lỗi trong khi sử lý dữ liệu . Bạn hãy kiểm tra lại.";
                }
                lbError.Text = error;
            }
            
        }

        protected void LoadDropParentCategory()
        {
            try
            {
                dropParentCategory.Items.Clear();
                //dropParentCategory.Items.Add("[---]");

                List<Category> listParent = newsMana.GetParentCategoryAll(language.LanguagesID, modulCode);
                //foreach (var li in listParent)
                //{
                //    dropParentCategory.Items.Add(li.CategoryName);
                //}
                dropParentCategory.DataSource = newsMana.GetParentCategoryAll(language.LanguagesID, modulCode);
                dropParentCategory.DataTextField = "CategoryName";
                dropParentCategory.DataValueField = "CategoryID";
                dropParentCategory.DataBind();
                dropParentCategory.Items.Insert(0,new ListItem("[--------]", "0"));
            }
            catch (Exception)
            {
                fail.Visible = true;
                if (error != string.Empty)
                {
                    error = "Có lỗi trong khi sử lý dữ liệu . Bạn hãy kiểm tra lại.";
                }
                lbError.Text = error;
            }
        }

        //protected void UpLoadFile()
        //{
        //    #region Upload file
        //    Boolean fileOK = false;
        //    String path = Server.MapPath(ConfigurationManager.AppSettings["FolderImagesUpload"]);

        //    string typeFile;
        //    if (imgUpload.HasFile)
        //    {
        //        String fileExtension = Path.GetExtension(imgUpload.FileName).ToLower();

        //        fileOK = true;

        //        if (fileOK)
        //        {
        //            if (fileExtension.ToString() == ".jpg" || fileExtension.ToString() == ".JPG" || fileExtension.ToString() == ".png" || fileExtension.ToString() == ".PNG" || fileExtension.ToString() == ".GIF" || fileExtension.ToString() == ".gif" || fileExtension.ToString() == ".bmp" || fileExtension.ToString() == ".BMP")
        //            {
        //                try
        //                {
        //                    Random rd = new Random(1000000);
        //                    int index = imgUpload.FileName.LastIndexOf('.');
        //                    typeFile = imgUpload.FileName.Substring(index - 1);

        //                    strFileName = "Picture_" + Convert.ToString(rd.Next(1000000, 9999999)) + typeFile;

        //                    imgUpload.PostedFile.SaveAs(path + strFileName);

        //                }
        //                catch (Exception ex)
        //                {
        //                    Console.Write(ex);
        //                }
        //            }
        //            else
        //            {
        //                fail.Visible = false;
        //                lbError.Text = "File của bạn không hợp lệ !";
        //            }

        //        }
        //    }
        //    #endregion 
        //}

        protected bool GetData()
        {
            if (txtCategoryName.Text.Trim() != "")
            {
                category.CategoryName = txtCategoryName.Text;
            }
            else
            {
                fail.Visible = true;
                error = "Tên của Danh mục bắt buộc phải có !";
                return false;
            }

            if (txtCategoryIntro.Text.Trim() != "")
            {
                if (TextBoxCounterCategoryIntro.Characters > int.Parse(ConfigurationManager.AppSettings["MaxIntroduction"].ToString()))
                {
                    fail.Visible = true;
                    error = "Lời giới thiệu không cho phép vượt quá " + ConfigurationManager.AppSettings["MaxIntroduction"].ToString() + " ký tự.";
                    return false;
                }
                else
                {
                    category.CategoryIntro = txtCategoryIntro.Text;
                }
            }
            else
            {
                category.CategoryIntro = "";
            }

            if (txtCategoryDes.Value.ToString() != "")
            {

                category.CategoryDes = txtCategoryDes.Value.ToString();

            }
            else
            {
                category.CategoryDes = "";
            }

            if (checkStatus.Checked == true)
            {
                category.CategoryStatus = true;
            }
            else
            {
                category.CategoryStatus = false;
            }

            category.LanguagesID = language.LanguagesID;

            if (dropParentCategory.SelectedValue == "0")
            {
                category.ParentCategoryID = 0;
            }
            else
            {
                //Category ca = newsMana.GetCategoryByNameSingle(dropParentCategory.SelectedValue.ToString(), modulCode);
                Category ca = newsMana.GetCategoryByID(int.Parse(dropParentCategory.SelectedValue.ToString()), modulCode);
                category.ParentCategoryID = ca.CategoryID;
            }

            if (Session[CONST.SESSION_IMG_THUMBNAIL] == null)
            {
                category.CategoryImg = "";
            }
            else
            {
                category.CategoryImg = ConfigurationManager.AppSettings["FolderImagesUpload"] + Session[CONST.SESSION_IMG_THUMBNAIL];
            }

            if (checkImgStatus.Checked)
            {
                ImgStatus = true;
            }
            else
            {
                ImgStatus = false;
            }

            return true;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (AddOrUp == false)
                {
                    #region Addnew

                    modulCode = Request.QueryString["Mod"];

                    category = new Category();

                    if (GetData() == false)
                        return;
                    //Tao danh muc
                    int idOut= newsMana.CreateCategory((int)category.ParentCategoryID, category.CategoryName, category.CategoryIntro, category.CategoryDes, category.CategoryImg, (Boolean)category.CategoryStatus,ImgStatus, (int)category.LanguagesID,modulCode);

                    //Tao metadata cho danh muc

                    Metadata meta=new Metadata();
                    meta.CategoryID = idOut;
                    newsMana.CreateMetadata(meta);

                    //Cap nhat meta cho danh muc vua tao
                    Response.Cookies[CONST.ACTION][CONST.COOKIES_ACTION_NAME] = "CreateMetadata";
                    Response.Cookies[CONST.ACTION][CONST.COOKIES_ACTION_TYPE] = "CreateNew";
                    Response.Redirect("Administrator.aspx?" + CONST.ACTION + "=CreateMetadata&Mod=" + modulCode +"&"+CONST.QUERYSTRING_CATEGORY+"="+idOut);

                    LoadDropParentCategory();
                    success.Visible = true;
                    lbSuccess.Text = "Bạn đã thêm mới danh mục thành công !";

                    this.FormatForm();
                    
                    #endregion
                }
                else
                {
                    #region Update

                    category = newsMana.GetCategoryByID(STRcategoryID,modulCode);

                    if (GetData() == false)
                        return;
                        

                    newsMana.UpdateCategory(STRcategoryID,(int)category.ParentCategoryID, category.CategoryName, category.CategoryIntro, category.CategoryDes, category.CategoryImg, (Boolean)category.CategoryStatus,ImgStatus, (int)category.LanguagesID,modulCode);

                    success.Visible = true;
                    lbSuccess.Text = "Bạn đã cập nhật danh mục thành công !";

                    this.FormatForm();

                    #endregion
                }   
            }
            catch (Exception)
            {
                fail.Visible = true;
                if(error!=string.Empty)
                    error = "Có lỗi trong khi sử lý dữ liệu . Bạn hãy kiểm tra lại.";

                lbError.Text = error;
            }        
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            this.FormatForm();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                category = newsMana.GetCategoryByID(STRcategoryID,modulCode);
                //List<New> listNews = newsMana.GetNewsByCategoryIDAll(category.CategoryID);
                //if (listNews.Count > 0)
                //{
                //    error = "Danh mục này có bài viết bạn không thể xóa!";
                //    lbError.Text = error;
                //    return;
                //}
                newsMana.DeleteCategory(category.CategoryID);

                //Danh mục giới thiệu
                Response.Cookies[CONST.ACTION][CONST.COOKIES_ACTION_NAME] = "CategoryNews";
                Response.Redirect("Administrator.aspx?" + CONST.ACTION + "=CategoryNews&Mod="+modulCode);
            }
            catch (Exception)
            {
                fail.Visible = true;
                if (error != string.Empty)
                    error = "Có lỗi trong khi sử lý dữ liệu . Bạn hãy kiểm tra lại.";

                lbError.Text = error;
            }
        }

        //protected void linkBack_Click(object sender, EventArgs e)
        //{
        //    Response.Cookies[CONST.ACTION][CONST.COOKIES_ACTION_NAME] = "CategoryNews";
        //    Response.Redirect("Administrator.aspx?" + CONST.ACTION + "=CategoryNews");
        //}

        protected void LoadForm()
        {
            try
            {
                category = newsMana.GetCategoryByID(STRcategoryID,modulCode);
                txtCategoryName.Text = category.CategoryName.ToString();

                if (category.CategoryIntro != null)
                    txtCategoryIntro.Text = category.CategoryIntro.ToString();
                else
                    txtCategoryIntro.Text = "";

                if (category.CategoryDes != null)
                    txtCategoryDes.Value = category.CategoryDes.ToString();
                else
                    txtCategoryDes.Value = "";

                dropLanguage.SelectedValue = languageMana.GetLanguageByID((int)category.LanguagesID).LanguagesID.ToString();
                if (newsMana.GetCategoryByParentCategoryID((int)category.CategoryID,modulCode) == null)
                {
                    dropParentCategory.SelectedValue = "[---]";
                }
                else
                    dropParentCategory.SelectedValue = newsMana.GetCategoryByParentCategoryID((int)category.CategoryID,modulCode).CategoryName.ToString();


                if (category.CategoryStatus == true)
                    checkStatus.Checked = true;
                else
                    checkStatus.Checked = false;

                if (category.CategoryImg != null)
                    imgCategory.ImageUrl = category.CategoryImg.ToString();
                else
                {
                    imgCategory.ImageUrl = ConfigurationManager.AppSettings["NoImages"];
                }

                if (category.ImagesStatus == true)
                {
                    checkImgStatus.Checked = true;
                }
                else
                    checkImgStatus.Checked = false;
                    
            }
            catch (Exception)
            {
                fail.Visible = true;
                if (error != string.Empty)
                    error = "Có lỗi trong khi sử lý dữ liệu . Bạn hãy kiểm tra lại.";

                lbError.Text = error;
            }
            
        }

    }
}